package com.cntaiping.royal.bass.system.controller;

import com.cntaiping.royal.bass.common.util.StringUtil;
import com.cntaiping.royal.bass.system.entity.SysResource;
import com.cntaiping.royal.bass.system.service.SysResourceService;
import com.cntaiping.royal.bass.system.util.UserUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * Created by FCHEN on 2016/12/23.
 */
@Controller
@RequestMapping(value = "resource")
public class ResourceController extends BaseController {

    @Autowired
    private SysResourceService sysResourceService;

    @ModelAttribute("sysResource")
    public SysResource get(@RequestParam(required=false) Long id) {
        if ( id != null ){
            SysResource sysResource = sysResourceService.queryById(id);
            return sysResource;
        }else{
            return new SysResource();
        }
    }

    @RequestMapping(value = {"list", ""})
    public String list(Model model) {
        List<SysResource> list = Lists.newArrayList();
        List<SysResource> sourcelist = UserUtils.getMenuList();
        SysResource.sortList(list, sourcelist, SysResource.getRootId(), true);
        model.addAttribute("list", list);
        return "sys/resource/list";
    }

    @RequestMapping(value = "form")
    public String form(SysResource sysResource, Model model) {
        if (sysResource.getParent()==null||sysResource.getParent().getId()==null){
            sysResource.setParent(new SysResource(SysResource.getRootId()));
        }
        sysResource.setParent(sysResourceService.queryById(sysResource.getParent().getId()));
        // 获取排序号，最末节点排序号+30
        if (sysResource.getId() == null ){
            List<SysResource> list = Lists.newArrayList();
            List<SysResource> sourcelist = UserUtils.getMenuList();
            sysResource.sortList(list, sourcelist, sysResource.getParentId(), false);
            if (list.size() > 0){
                sysResource.setSeq(list.get(list.size()-1).getSeq() + 30);
            }
        }
        model.addAttribute("sysResource", sysResource);
        return "sys/resource/edit";
    }

    @RequestMapping(value = "save")
    public String save(SysResource sysResource) {
        sysResource.setOperator(UserUtils.getUser().getId());
        sysResourceService.saveReSource(sysResource);
        // 清除用户菜单缓存
//        UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
        // 清除日志相关缓存
//        CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
        return "redirect:list";
    }

    @RequestMapping(value = "treeselect")
    public String treeselect(String parentId, Model model) {
        model.addAttribute("parentId", parentId);
        return "sys/resource/menuTreeselect";
    }

    @RequestMapping(value = "delete")
    @ResponseBody
    public Object delete(SysResource sysResource) {
        sysResourceService.delete(sysResource);
        // 清除用户菜单缓存
//        UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
        // 清除日志相关缓存
//        CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
        String result = "删除菜单成功!";
//        addMessage(redirectAttributes, "删除菜单成功");
        return result;
    }

    /**
     * 批量修改菜单排序
     */
    @RequestMapping(value = "updateSort")
    public String updateSort(Long[] ids, Integer[] seq, RedirectAttributes redirectAttributes) {
        for (int i = 0; i < ids.length; i++) {
            SysResource sysResource = new SysResource(ids[i]);
            sysResource.setSeq(seq[i]);
            sysResourceService.updateSort(sysResource);
            // 清除用户菜单缓存
//            UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
            // 清除日志相关缓存
//            CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
        }
        addMessage(redirectAttributes, "保存菜单排序成功!");
        return "redirect:list";
    }

    /**
     * isShowHide是否显示隐藏菜单
     * @param extId
     * @param isShowHide
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "treeData")
    public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, @RequestParam(required=false) String isShowHide, HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<SysResource> list = UserUtils.getMenuList();
        for (int i=0; i<list.size(); i++){
            SysResource e = list.get(i);

            if (StringUtil.isBlank(extId) || (extId!=null && !extId.equals(e.getId()+"") && e.getParentIds().indexOf(","+extId+",")==-1)){
                if(isShowHide != null && isShowHide.equals("0") && !e.getIsShow()){
                    continue;
                }
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e.getId());
                map.put("pId", e.getParentId());
                map.put("name", e.getName());
                mapList.add(map);
            }
        }
        return mapList;
    }
}
